import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const store_id = localStorage.getItem('store_id')

interface storeItem {
  storeName: string
  avatar: string
  memberName: string
  memberId: string
  mobile: string
  idNumber: string
  carModelId: string
  isExamRoomVip: number
}

// 用户
export const useUserStore = defineStore(
  'userStore',
  () => {
    const router = useRouter()
    const accessToken = ref('')
    const refreshToken = ref('')
    const storeInfo = ref<Partial<storeItem>>({})
    const pageForm = ref<any>('') // 添加pageForm状态
    const formattedTime = ref('')
    const showTimer = ref(false) // 控制是否显示
    const categoryId = ref()
    const statisticsData = ref<any>({})
    const activeTab = ref(0) //控制首页类目tab
    const wrongList = ref<any>()
    const setToken = (newAccessToken: string, newRefreshToken?: string) => {
      accessToken.value = newAccessToken
      if (newRefreshToken) {
        refreshToken.value = newRefreshToken
      }
    }
    const setStoreInfo = (info: object) => {
      storeInfo.value = info
    }
    const setShowTimer = (params: { showTimer?: boolean; formattedTime?: string }) => {
      if (params.showTimer !== undefined) {
        showTimer.value = params.showTimer
      }
      if (params.formattedTime !== undefined) {
        formattedTime.value = params.formattedTime
      }
    }
    // 添加setPageForm方法
    const setPageForm = (formData: any) => {
      pageForm.value = formData
    }
    const setCategoryId = (id: number) => {
      categoryId.value = id
    }
    const setStatisticsData = (obj: object) => {
      statisticsData.value = obj
    }
    const setActiveTab = (index: number) => {
      activeTab.value = index
    }

    const setWrongList = (e: any) => {
      wrongList.value = e
    }

    const logOut = () => {
      accessToken.value = ''
      refreshToken.value = ''
      router.push({
        path: '/login',
        query: { store_id },
      })
    }

    const clearToken = () => {
      accessToken.value = ''
      refreshToken.value = ''
      storeInfo.value = {}
      pageForm.value = '' // 清空pageForm
      activeTab.value = 0
      categoryId.value = ''
      statisticsData.value = {}
    }

    return {
      accessToken,
      refreshToken,
      storeInfo,
      pageForm, // 导出pageForm
      formattedTime,
      showTimer,
      categoryId,
      statisticsData,
      activeTab,
      wrongList,
      setToken,
      logOut,
      clearToken,
      setStoreInfo,
      setShowTimer,
      setPageForm,
      setCategoryId, // 导出setPageForm方法
      setStatisticsData,
      setActiveTab,
      setWrongList
    }
  },
  {
    persist: {
      key: 'user',
      storage: localStorage,
    },
  },
)
